package cn.chiship.framework.business.biz.business.service.impl;

import cn.chiship.framework.business.biz.business.entity.*;
import cn.chiship.framework.business.biz.business.mapper.BusinessFormMapper;
import cn.chiship.framework.business.biz.business.pojo.vo.BusinessFormValueVo;
import cn.chiship.framework.business.biz.content.pojo.vo.ContentArticleVo;
import cn.chiship.framework.upms.biz.system.service.UpmsCategoryDictService;
import cn.chiship.sdk.core.base.BaseResult;
import cn.chiship.sdk.core.exception.custom.BusinessException;
import cn.chiship.sdk.core.util.DateUtils;
import cn.chiship.sdk.core.util.PrintUtil;
import cn.chiship.sdk.core.util.StringUtil;
import cn.chiship.sdk.framework.base.BaseServiceImpl;
import cn.chiship.framework.business.biz.business.mapper.BusinessFormValueMapper;
import cn.chiship.framework.business.biz.business.service.BusinessFormValueService;
import cn.chiship.sdk.framework.pojo.dto.export.ExportDto;
import cn.chiship.sdk.framework.pojo.dto.export.ExportTransferDataDto;
import cn.chiship.sdk.framework.pojo.vo.PageVo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.page.PageMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 自封有表单提交数据业务接口实现层
 * 2024/12/13
 *
 * @author lijian
 */
@Service
public class BusinessFormValueServiceImpl extends BaseServiceImpl<BusinessFormValue, BusinessFormValueExample> implements BusinessFormValueService {

    private static final Logger LOGGER = LoggerFactory.getLogger(BusinessFormValueServiceImpl.class);

    @Resource
    BusinessFormValueMapper businessFormValueMapper;
    @Resource
    BusinessFormMapper businessFormMapper;
    @Resource
    UpmsCategoryDictService upmsCategoryDictService;

    @Override
    public BaseResult page(PageVo pageVo, Map<String, String> paramsMap) {
        Page<Object> pageResult = PageMethod.startPage(pageVo.getCurrent().intValue(), pageVo.getSize().intValue());
        List<BusinessFormValueVo> businessFormValueVos = businessFormValueMapper.selectBaseContentDetail(paramsMap);
        List<JSONObject> results = new ArrayList<>();
        for (BusinessFormValueVo vo : businessFormValueVos) {
            JSONObject json = JSON.parseObject(JSON.toJSONString(vo));
            json.putAll(upmsCategoryDictService.getParentInfoById(vo.getCategoryId()));
            results.add(json);
        }
        pageVo.setRecords(results);
        pageVo.setTotal(pageResult.getTotal());
        pageVo.setPages((long) pageResult.getPages());
        return BaseResult.ok(pageVo);
    }

    @Override
    public PageVo selectPageByExample(PageVo pageVo, BusinessFormValueExample businessFormValueExample) {
        String sort = pageVo.getSort();
        Page page = PageMethod.startPage(pageVo.getCurrent().intValue(), pageVo.getSize().intValue());
        PageMethod.orderBy(sort);
        List<BusinessFormValue> businessFormValues = businessFormValueMapper.selectByExampleWithBLOBs(businessFormValueExample);
        pageVo.setRecords(businessFormValues);
        pageVo.setTotal(page.getTotal());
        pageVo.setPages(Long.valueOf(page.getPages()));
        return pageVo;
    }

    @Override
    public BaseResult selectDetailsByPrimaryKey(Object id) {
        BusinessFormValueExample businessFormValueExample = new BusinessFormValueExample();
        businessFormValueExample.createCriteria().andIdEqualTo(id.toString());
        List<BusinessFormValue> businessFormValues = businessFormValueMapper.selectByExampleWithBLOBs(businessFormValueExample);
        if (businessFormValues.isEmpty()) {
            return BaseResult.error("暂无表单数据");
        }
        BusinessFormValue businessFormValue = businessFormValues.get(0);


        BusinessFormExample businessFormExample = new BusinessFormExample();
        businessFormExample.createCriteria().andIdEqualTo(businessFormValue.getFormId());
        List<BusinessForm> businessForms = businessFormMapper.selectByExampleWithBLOBs(businessFormExample);
        if (businessForms.isEmpty()) {
            return BaseResult.ok();
        }
        BusinessForm businessForm = businessForms.get(0);
        if (StringUtil.isNullOrEmpty(businessForm.getFormContent())) {
            return BaseResult.error("表单设计数据缺失");
        }
        JSONObject json = JSON.parseObject(JSON.toJSONString(businessFormValue));
        json.put("formName", businessForm.getName());
        json.put("formContent", businessForm.getFormContent());
        json.put("formOptions", businessForm.getFormOptions());
        return BaseResult.ok(json);

    }

    @Override
    public BaseResult insertSelective(BusinessFormValue businessFormValue) {
        BusinessForm businessForm = businessFormMapper.selectByPrimaryKey(businessFormValue.getFormId());
        if (StringUtil.isNull(businessForm)) {
            return BaseResult.error("表单【" + businessFormValue.getFormId() + "】不存在!");
        }
        businessFormValue.setFormCode(businessForm.getCode());
        return super.insertSelective(businessFormValue);
    }

    @Override
    public ExportTransferDataDto assemblyExportData(ExportDto exportDto) {
        Map<String, Object> paramMap = exportDto.getParamMap();
        if (!paramMap.containsKey("formId")) {
            throw new BusinessException("缺少formId参数");
        }
        String formId = paramMap.get("formId").toString();

        BusinessFormExample businessFormExample = new BusinessFormExample();
        businessFormExample.createCriteria().andIdEqualTo(formId);
        List<BusinessForm> businessForms = businessFormMapper.selectByExampleWithBLOBs(businessFormExample);
        if (businessForms.isEmpty()) {
            throw new BusinessException("无效的表单资源");
        }
        BusinessForm businessForm = businessForms.get(0);
        if (StringUtil.isNullOrEmpty(businessForm.getFormContent())) {
            throw new BusinessException("表单设计数据缺失");
        }
        JSONArray jsonFromContent = JSON.parseArray(businessForm.getFormContent());

        String fileName = businessForm.getName() + "数据清单";
        String sheetName = businessForm.getName();
        String sheetTitle = "【" + businessForm.getName() + "】数据收集清单";
        List<String> labels = new ArrayList<>();
        List<List<String>> valueList = new ArrayList<>();
        labels.add("填报人姓名");
        labels.add("填报人手机号");
        for (int i = 0; i < jsonFromContent.size(); i++) {
            JSONObject json = jsonFromContent.getJSONObject(i);
            labels.add(json.getString("title"));
        }
        labels.add("新增时间");
        labels.add("最后修改时间");
        BusinessFormValueExample businessFormValueExample = new BusinessFormValueExample();
        businessFormValueExample.createCriteria().andFormIdEqualTo(formId);
        businessFormValueExample.setOrderByClause(StringUtil.getOrderByValue(paramMap.get("sort").toString()));
        List<BusinessFormValue> businessFormValues = businessFormValueMapper.selectByExampleWithBLOBs(businessFormValueExample);
        for (BusinessFormValue businessFormValue : businessFormValues) {
            List<String> values = new ArrayList<>();
            values.add(businessFormValue.getCreatedUserRealName());
            values.add(businessFormValue.getCreatedUserMobile());
            JSONObject dataJson = JSON.parseObject(businessFormValue.getFormValue());
            for (int i = 0; i < jsonFromContent.size(); i++) {
                JSONObject jsonContent = jsonFromContent.getJSONObject(i);
                String field = jsonContent.getString("field");
                //String type = jsonContent.getString("type");
                if (dataJson.containsKey(field)) {
                    values.add(dataJson.get(field).toString());
                } else {
                    values.add("");
                }
            }

            values.add(DateUtils.dateTime(businessFormValue.getGmtCreated()));
            values.add(DateUtils.dateTime(businessFormValue.getGmtModified()));
            valueList.add(values);
        }

        return new ExportTransferDataDto(fileName, sheetName, sheetTitle, labels, valueList, valueList.size());
    }

    public static void main(String[] args) {
        String s = "[{\"type\":\"input\",\"field\":\"totalMoney\",\"title\":\"报销总金额\",\"info\":\"\",\"props\":{\"type\":\"number\",\"placeholder\":\"请输入数字\"},\"_fc_drag_tag\":\"input\",\"hidden\":false,\"display\":true,\"value\":\"\",\"$required\":\"请填写报销总金额\"},{\"type\":\"input\",\"field\":\"pcb\",\"title\":\"用途及费用明细\",\"info\":\"\",\"props\":{\"type\":\"textarea\",\"showWordLimit\":false,\"placeholder\":\"请输入费用类别及明细\"},\"_fc_drag_tag\":\"input\",\"hidden\":false,\"display\":true,\"$required\":\"请填写用途及费用明细\"},{\"type\":\"input\",\"field\":\"originalNumber\",\"title\":\"原始凭证张数\",\"info\":\"\",\"props\":{\"type\":\"number\",\"placeholder\":\"请输入数字\"},\"_fc_drag_tag\":\"input\",\"hidden\":false,\"display\":true,\"$required\":\"\",\"validate\":[{\"trigger\":\"blur\",\"mode\":\"required\",\"message\":\"请输入原始凭证张数\",\"required\":true,\"type\":\"number\"}]},{\"type\":\"upload\",\"field\":\"billFare\",\"title\":\"费用单据\",\"info\":\"\",\"props\":{\"action\":\"${fileServer}\",\"onSuccess\":\"[[FORM-CREATE-PREFIX-function(e,t){Vue.prototype.formCreaterUploadSuccess(e,t)}-FORM-CREATE-SUFFIX]]\",\"headers\":{\"ProjectsId\":\"${ProjectsId}\",\"Access-Token\":\"${Access-Token}\"}},\"_fc_drag_tag\":\"upload\",\"hidden\":false,\"display\":true,\"$required\":false},{\"type\":\"input\",\"field\":\"remark\",\"title\":\"备注\",\"info\":\"\",\"props\":{\"type\":\"textarea\",\"placeholder\":\"请输入\",\"showWordLimit\":true,\"maxlength\":200},\"_fc_drag_tag\":\"input\",\"hidden\":false,\"display\":true}]";
        String s1 = "{\"totalMoney\":\"1\",\"pcb\":\"1111\",\"originalNumber\":\"1\",\"billFare\":[\"6e5295efafb94f79ad6e2669b625d8d3\"]}";
        JSONArray jsonFromContent = JSON.parseArray(s);
        JSONObject dataJson = JSON.parseObject(s1);
        for (int i = 0; i < jsonFromContent.size(); i++) {
            JSONObject json = jsonFromContent.getJSONObject(i);
            String field = json.getString("field");
            String type = json.getString("type");
            if (dataJson.containsKey(field)) {
                System.out.println(dataJson.get(field) + type);
            } else {
                System.out.println(field);
            }
        }
    }
}
